import json
from random import random

from bs4 import BeautifulSoup
from loguru import logger


class YifenYiduanParser:
    def __init__(self):
        super().__init__()

    def parse_yifen_yiduan_list(self, povince_map):
        query_list = []
        year_code_arr = range(2016, 2022)
        for povince in povince_map:
            for year_code in year_code_arr:
                # 0-100 之间的随机整数
                random_num = int(random() * 100)
                p_code = povince_map[povince]
                item_url = f"http://www.juzhiyuan.com/yifenyiduan?rand={random_num}&province={p_code}&year={year_code}"
                query_list.append({
                    "url": item_url,
                    "povince_name": povince,
                    "povince_code": p_code,
                    "year_code": year_code,
                })
        return query_list

    def parse_yifen_yiduan_detail_list(self, segment, html):
        soup = BeautifulSoup(html, "lxml")
        div_tag = soup.find("div", {"class": "yfydsx"})
        items = div_tag.find("div", {"id": "kemu"}).find_all("a")
        batch = div_tag.find("div", {"id": "batch"})
        resutl_list = []
        logger.info("获取分段：{}", segment)
        try:
            for item in items:
                if batch is not None:
                    for batch_item in batch.find_all("a"):
                        resutl_list.append({
                            "url": segment.get("url") + "&kemu=" + item.attrs["val"] + "&batch=" + batch_item.attrs[
                                "val"],
                            "povince_name": segment.get("povince_name"),
                            "povince_code": segment.get("povince_code"),
                            "year_code": segment.get("year_code"),
                            "score_category": item.text,
                            "edu_level": batch_item.text,
                        })
                resutl_list.append({
                    "url": segment.get("url") + "&kemu=" + item.attrs["val"],
                    "povince_name": segment.get("povince_name"),
                    "povince_code": segment.get("povince_code"),
                    "year_code": segment.get("year_code"),
                    "score_category": item.text,
                })
            return resutl_list
        except Exception as e:
            logger.error(e)

    def parse_yifen_yiduan_result(self, segment, html):
        soup = BeautifulSoup(html, "lxml")
        yifentable = soup.find("div", {"class": "yifentable"}).find("table")
        tr_list = yifentable.find_all("tr")
        result_list = []
        for tr in tr_list:
            td_list = tr.find_all("td")
            if len(td_list) == 0:
                continue
            if "-" in td_list[0].text:
                score = td_list[0].text.split("-")[0]
            else:
                score = td_list[0].text
            result_list.append({
                "province": segment.get("povince_name"),
                "score_year": segment.get("year_code"),
                "score_category": segment.get("score_category"),
                "edu_level": "" if segment.get("edu_level") is None else segment.get("edu_level"),
                "score": score,
                "rank_segment": td_list[1].text,
                "same_score_person": td_list[2].text,
                "suggest_rank": td_list[3].text,
            })
        return result_list
